package org.zry.chat2ai.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.zry.chat2ai.entity.User;
import org.zry.chat2ai.repository.UserRepository;

import java.util.Optional;

@RestController
public class LoginController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestParam String username, @RequestParam String password) {
        Optional<User> userOptional = userRepository.findByUsernameAndPassword(username, password);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            return ResponseEntity.ok("登录成功，用户 ID: " + user.getId());
        } else {
            // 若用户不存在，则创建新用户
            User newUser = new User(username, password);
            User savedUser = userRepository.save(newUser);
            return ResponseEntity.ok("用户不存在，已创建新用户，用户 ID: " + savedUser.getId());
        }
    }
}
